<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <title>作品详情 - 数智化赋能“微情境·微宣讲”红色实践活动</title>


  <!-- 微信卡片分享必需的meta标签 -->
  <meta property="og:type" content="website">
  <meta property="og:site_name" content="数智化微宣讲">
  <meta property="og:title" content="数智化赋能'微情境·微宣讲'红色实践活动">
  <meta property="og:description" content="数智点亮红色传承，创新砥砺时代英才">
  <meta property="og:image" content="/templates/h5/assets/pictures/banner1.jpg">
  <meta property="og:url" content="https://shuidicms.cn/h5/index">


  <!-- 引入Swiper CSS -->
  <link rel="stylesheet" th:href="@{/templates/h5/assets/swiper-bundle.min.css}">
  <!-- 引入Tailwind CSS -->
  <script th:src="@{/templates/h5/assets/tailwindcss3.4.17.css}"></script>
  <!-- 引入Font Awesome -->
  <link th:href="@{/templates/h5/assets/font-awesome-4.7.0/css/font-awesome.min.css}" rel="stylesheet">
  <script th:src="@{/templates/h5/assets/jquery.min.js}"></script>

  <script>
    // 配置Tailwind自定义颜色（红色主题）
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#b71211', // 主红色
            secondary: '#FFD700', // 辅助金色
            red: {
              700: '#B91C1C',    // 稍浅红色
              800: '#991B1B',    // 深一点的红色
              900: '#7F1D1D',    // 最深红色
            }
          },
        },
      }
    }
  </script>

  <style type="text/tailwindcss">
    @layer utilities {
      /* 导航栏样式 */
      .nav-item {
        @apply flex flex-col items-center justify-center text-gray-300 active:bg-red-800 h-full;
      }
      .nav-item.active {
        @apply text-white;
      }
      .nav-icon {
        @apply text-lg mb-1;
      }
      .nav-text {
        @apply text-xs;
      }

      /* 内容区块样式 */
      .content-section {
        @apply bg-red-800 rounded-lg p-4 mb-4 border border-red-700;
      }

      /* 视频容器样式 */
      .video-container {
        @apply relative w-full bg-red-900 rounded-lg overflow-hidden mb-4;
        padding-top: 56.25%; /* 16:9比例 */
      }
      .video-placeholder {
        @apply absolute inset-0 flex items-center justify-center;
      }
      .video-player {
        @apply absolute inset-0 w-full h-full object-contain;
      }

      /* 评分标签样式 */
      .score-tag {
        @apply bg-red-900 px-2 py-1 rounded text-sm inline-flex items-center mr-2 mb-2;
      }
      .edit-btn {
        @apply ml-1 text-secondary text-xs cursor-pointer hover:opacity-80;
      }

      /* 互动按钮样式 */
      .action-btn {
        @apply flex flex-col items-center justify-center text-gray-200;
      }
      .action-btn.active {
        @apply text-secondary;
      }
      .action-icon {
        @apply text-lg mb-1;
      }
      .action-text {
        @apply text-xs;
      }

      /* 评论样式 */
      .comment-item {
        @apply border-b border-red-700 pb-3 mb-3 last:border-0 last:pb-0 last:mb-0;
      }
      .comment-avatar {
        @apply w-8 h-8 rounded-full bg-red-700 flex items-center justify-center text-xs mr-2;
      }

      /* 弹窗样式 */
      .modal-overlay {
        @apply fixed inset-0 bg-black/70 flex items-center justify-center z-50 opacity-0 pointer-events-none transition-opacity duration-300;
      }
      .modal-overlay.active {
        @apply opacity-100 pointer-events-auto;
      }
      .modal-container {
        @apply bg-red-800 border border-red-700 rounded-xl w-11/12 max-w-sm transform scale-95 transition-transform duration-300;
      }
      .modal-overlay.active .modal-container {
        @apply scale-100;
      }
      .modal-header {
        @apply border-b border-red-700 px-5 py-4 flex justify-between items-center;
      }
      .modal-body {
        @apply px-5 py-4;
      }
      .modal-footer {
        @apply border-t border-red-700 px-5 py-3 flex justify-end gap-2;
      }
      .score-input {
        @apply w-full bg-red-900 border border-red-700 rounded-lg px-3 py-2 text-white mt-2 focus:outline-none focus:border-secondary;
      }
      .modal-note {
        @apply text-xs text-gray-300 mt-2 italic;
      }
      .btn-primary {
        @apply bg-secondary text-red-900 px-4 py-1.5 rounded-lg text-sm font-medium hover:bg-secondary/90 transition-colors;
      }
      .btn-secondary {
        @apply bg-red-900 text-white px-4 py-1.5 rounded-lg text-sm font-medium hover:bg-red-700 transition-colors;
      }

      /* 加载状态 */
      .loading {
        @apply text-center py-8 text-gray-300;
      }
    }
  </style>
</head>
<body class="bg-primary text-white">
<div class="max-w-md mx-auto min-h-screen flex flex-col">
  <!-- 页面标题栏 -->
  <div class="py-4 px-4 border-b border-red-700 bg-red-900 flex justify-between items-center">
    <a href="#" class="text-white"><i class="fa fa-arrow-left"></i></a>
    <h1 class="text-xl font-bold">作品详情</h1>
    <a href="javascript:;" class="text-white" id="topShareBtn"><i class="fa fa-share-alt"></i></a>
  </div>

  <!-- 页面内容区 -->
  <div class="flex-1 overflow-y-auto p-4 pb-24">
    <!-- 作品基本信息 -->
    <div class="content-section pb-3">
      <div class="flex justify-between items-start mb-3">
        <div>
          <span class="text-xs bg-red-900 px-2 py-0.5 rounded" th:text="|序号: #${compWork.id}|"  style="display: none;"></span>
          <h2 class="text-lg font-bold mt-1" th:text="${compWork.workName} ?: '未命名作品'"></h2>
        </div>
        <span class="bg-secondary text-red-900 text-xs px-2 py-1 rounded-full font-medium" th:text="|综合排名: 第${compWork.index ?: 'N'}名|" style="display: none;"></span>
      </div>

      <!-- 作品封面 -->
      <div class="w-full rounded-lg overflow-hidden mb-3">
        <img
                th:src="${compWork.workCover ?: ('https://picsum.photos/800/450?random=' + compWork.id)}"
                th:alt="${compWork.workName}"
                class="w-full"
                loading="lazy"
        >
      </div>

      <!-- 评分信息 -->
      <div>
        <div class="flex flex-wrap">
          <div class="score-tag">
            <i class="fa fa-star text-secondary mr-1"></i>
            <span th:text="|综合得分: ${compWork.totalScore ?: 0}|"></span>
          </div>
          <div class="score-tag">
            <i class="fa fa-users text-secondary mr-1"></i>
            <span th:text="|学生评分: ${compWork.studentScore ?: 0}|"></span>
            <span class="edit-btn" data-type="student" id="editStudentScore"><i class="fa fa-pencil"></i></span>
          </div>
          <div class="score-tag">
            <i class="fa fa-graduation-cap text-secondary mr-1"></i>
            <span th:text="|教师评分: ${compWork.teacherScore ?: 0}|"></span>
            <span class="edit-btn" data-type="teacher" id="editTeacherScore"><i class="fa fa-pencil"></i></span>
          </div>
        </div>
      </div>
    </div>

    <!-- 微情境视频 -->
    <div class="content-section">
      <h3 class="text-base font-medium mb-3 flex items-center">
        <i class="fa fa-film text-secondary mr-2"></i>微情境视频
      </h3>
      <div class="video-container">
        <div class="video-placeholder" id="situationVideoPlaceholder"  style="display: none;">
          <button class="w-14 h-14 rounded-full bg-secondary/90 text-red-900 flex items-center justify-center">
            <i class="fa fa-play text-xl"></i>
          </button>
        </div>
        <video
                th:if="${compWork.workVideo1}"
                class="video-player hidden"
                id="situationVideo"
                controls
                autoplay
                muted
                playsinline
                th:src="${compWork.workVideo1}"
        >
          您的浏览器不支持视频播放
        </video>
      </div>
      <p class="text-xs text-gray-300 text-center" th:text="|点击播放|"></p>
    </div>

    <!-- 微宣讲视频 -->
    <div class="content-section">
      <h3 class="text-base font-medium mb-3 flex items-center">
        <i class="fa fa-video-camera text-secondary mr-2"></i>微宣讲视频
      </h3>
      <div class="video-container">
        <div class="video-placeholder" id="speechVideoPlaceholder" style="display: none;">
          <button class="w-14 h-14 rounded-full bg-secondary/90 text-red-900 flex items-center justify-center">
            <i class="fa fa-play text-xl"></i>
          </button>
        </div>
        <video
                th:if="${compWork.workVideo2}"
                class="video-player hidden"
                id="speechVideo"
                controls
                th:src="${compWork.workVideo2}"
        >
          您的浏览器不支持视频播放
        </video>
      </div>
      <p class="text-xs text-gray-300 text-center" th:text="|点击播放|"></p>
    </div>

    <!-- 作品数据与互动 -->
    <div class="content-section">
      <div class="flex justify-around py-2">
        <button class="action-btn" id="likeBtn">
          <i class="action-icon fa fa-thumbs-up"></i>
          <span class="action-text" th:text="|点赞 (${compWork.likeCount ?: 0})|"></span>
        </button>
        <button class="action-btn">
          <i class="action-icon fa fa-eye"></i>
          <span class="action-text" th:text="|浏览 (${(compWork.lookCount ?: 0)})|"></span>
        </button>
        <button class="action-btn" id="shareBtn">
          <i class="action-icon fa fa-share"></i>
          <span class="action-text" th:text="|转发 (${(compWork.shareCount ?: 0)})|"></span>
        </button>
      </div>
    </div>

    <!-- 在线评论 -->
    <div class="content-section">
      <h3 class="text-base font-medium mb-3 flex items-center">
        <i class="fa fa-comments text-secondary mr-2"></i>
        <span th:text="|在线评论 (${compWork.commentCount ?: 0})|"></span>
      </h3>

      <!-- 评论输入框 -->
      <div class="flex mb-4">
        <div class="comment-avatar">
          <i class="fa fa-user"></i>
        </div>
        <div class="flex-1">
          <input type="text" placeholder="发表你的看法..." class="w-full bg-red-900 border border-red-700 rounded-full px-3 py-2 text-sm focus:outline-none focus:border-secondary" id="commentInput">
        </div>
      </div>

<!--      <div class="comment-list">-->
<!--        <div class="comment-item" th:each="comment : ${comments}" th:data-comment-id="${comment.id}">-->
<!--          <div class="flex">-->
<!--            <div class="comment-avatar">-->
<!--              <span th:text="${#strings.substring(comment.userName, 0, 1)}"></span>-->
<!--            </div>-->
<!--            <div class="flex-1">-->
<!--              <div class="flex justify-between">-->
<!--                <div class="font-medium text-sm" th:text="${comment.userName}"></div>-->
<!--                <div class="text-xs text-gray-400" th:text="${#dates.format(comment.commentTime, 'yyyy-MM-dd HH:mm')}"></div>-->
<!--              </div>-->
<!--              <p class="text-sm mt-1" th:text="${comment.content}"></p>-->
<!--              <div class="flex mt-2 text-xs text-gray-400">-->
<!--                <button class="flex items-center mr-3 comment-like-btn" th:data-comment-id="${comment.id}">-->
<!--                  <i class="fa fa-thumbs-up mr-1"></i>-->
<!--                  <span th:text="${comment.likeCount ?: 0}"></span>-->
<!--                </button>-->
<!--                <button class="reply-btn" th:data-comment-id="${comment.id}">回复</button>-->
<!--              </div>-->
<!--            </div>-->
<!--          </div>-->
<!--        </div>-->

      <!-- 评论列表 -->
      <div class="comment-list">
        <!-- 顶级评论容器 -->
        <div class="top-comments">
          <!-- 通过Thymeleaf循环渲染所有顶级评论（pid为null或0） -->
          <div class="comment-item" th:each="comment : ${comments}" th:if="${comment.pid == null or comment.pid == 0}" th:data-comment-id="${comment.id}">
            <div class="flex">
              <div class="comment-avatar">
                <span th:text="${#strings.substring(comment.userName, 0, 1)}"></span>
              </div>
              <div class="flex-1">
                <div class="flex justify-between">
                  <div class="font-medium text-sm" th:text="${comment.userId}"></div>
                  <div class="text-xs text-gray-400" th:text="${#dates.format(comment.commentTime, 'yyyy-MM-dd HH:mm')}"></div>
                </div>
                <p class="text-sm mt-1" th:text="${comment.content}"></p>
                <div class="flex mt-2 text-xs text-gray-400">
                  <button class="flex items-center mr-3 comment-like-btn" th:data-comment-id="${comment.id}">
                    <i class="fa fa-thumbs-up mr-1"></i>
                    <span th:text="${comment.likeCount ?: 0}"></span>
                  </button>
                  <button class="reply-btn" th:data-comment-id="${comment.id}" th:data-user-name="${comment.userId}">
                    回复
                  </button>
                </div>

                <!-- 子评论容器（通过pid关联父评论） -->
                <div class="child-comments mt-3 pl-4 border-l-2 border-red-700/50">
                  <div class="comment-item" th:each="child : ${comment.child}" th:data-comment-id="${child.id}">
                    <div class="flex">
                      <div class="comment-avatar">
                        <span th:text="${#strings.substring(child.userName, 0, 1)}"></span>
                      </div>
                      <div class="flex-1">
                        <div class="flex justify-between">
                          <div class="font-medium text-sm" th:text="${child.userId}"></div>
                          <div class="text-xs text-gray-400" th:text="${#dates.format(child.commentTime, 'yyyy-MM-dd HH:mm')}"></div>
                        </div>
                        <p class="text-sm mt-1">
                          <span class="text-secondary">@[[${#strings.substring(comment.userName, 0)}]]</span>
                          <span th:text="${child.content}"></span>
                        </p>
                        <div class="flex mt-2 text-xs text-gray-400">
                          <button class="flex items-center mr-3 comment-like-btn" th:data-comment-id="${child.id}">
                            <i class="fa fa-thumbs-up mr-1"></i>
                            <span th:text="${child.likeCount ?: 0}"></span>
                          </button>
<!--                          <button class="reply-btn" th:data-comment-id="${child.id}" th:data-user-name="${child.userId}">-->
<!--                            回复-->
<!--                          </button>-->
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>






        <!-- 默认评论（当没有评论数据时显示） -->
        <div class="comment-item" th:if="${comments == null or comments.isEmpty()}">
          <div class="flex">
            <div class="comment-avatar">
              <span>张</span>
            </div>
            <div class="flex-1">
              <div class="flex justify-between">
                <div class="font-medium text-sm">张明</div>
                <div class="text-xs text-gray-400">2天前</div>
              </div>
              <p class="text-sm mt-1">作品非常感人，让我深刻理解了革命先辈的奋斗精神，值得我们学习和传承。</p>
              <div class="flex mt-2 text-xs text-gray-400">
                <button class="flex items-center mr-3 comment-like-btn" data-comment-id="0">
                  <i class="fa fa-thumbs-up mr-1"></i> 128
                </button>
                <button class="reply-btn" data-comment-id="0">回复</button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 加载更多评论 -->
      <button class="w-full mt-3 py-2 text-sm border border-red-700 rounded-full hover:bg-red-900 transition-colors" id="loadMoreCommentsBtn">
        加载更多评论
      </button>
    </div>
  </div>

  <!-- 底部固定导航栏 -->
  <div class="fixed bottom-0 left-0 right-0 max-w-md mx-auto bg-red-900 border-t border-red-700 z-50 h-16 flex">
    <a href="/h5/index" class="nav-item active flex-1">
      <i class="nav-icon fa fa-home"></i>
      <span class="nav-text">首页</span>
    </a>
    <a href="/h5/index_huodong" class="nav-item flex-1">
      <i class="nav-icon fa fa-calendar"></i>
      <span class="nav-text">活动</span>
    </a>
    <a href="/h5/index_paihangbang" class="nav-item flex-1">
      <i class="nav-icon fa fa-bar-chart"></i>
      <span class="nav-text">排行榜</span>
    </a>
    <a href="/h5/index_yonghu" class="nav-item flex-1">
      <i class="nav-icon fa fa-user"></i>
      <span class="nav-text">我的</span>
    </a>
  </div>
</div>

<!-- 评分编辑弹窗 -->
<div class="modal-overlay" id="scoreModal">
  <div class="modal-container">
    <div class="modal-header">
      <h3 class="font-bold text-base" id="modalTitle">编辑评分</h3>
      <button class="text-gray-300 hover:text-white" id="closeModal">
        <i class="fa fa-times"></i>
      </button>
    </div>
    <div class="modal-body">
      <p>请输入评分（1-100分）</p>
      <input type="number" min="1" max="100" step="0.1" class="score-input" id="scoreInput" th:value="${compWork.studentScore ?: 0}">
      <p class="modal-note" id="modalNote">
        提示：每个用户只能为同一作品评分一次
      </p>
    </div>
    <div class="modal-footer">
      <button class="btn-secondary" id="cancelBtn">取消</button>
      <button class="btn-primary" id="nextConfirmBtn">下一步</button>
    </div>
  </div>
</div>

<!-- 评分二次确认弹窗 -->
<div class="modal-overlay" id="scoreConfirmModal">
  <div class="modal-container">
    <div class="modal-header">
      <h3 class="font-bold text-base">确认评分</h3>
      <button class="text-gray-300 hover:text-white" id="closeScoreConfirmModal">
        <i class="fa fa-times"></i>
      </button>
    </div>
    <div class="modal-body text-center py-4">
      <i class="fa fa-exclamation-circle text-secondary text-2xl mb-3"></i>
      <p class="mb-2">您确定要提交这个评分吗？</p>
      <p class="text-sm">请确认无误后再提交，提交后无法修改</p>
      <p class="mt-3 font-medium" id="confirmScoreDisplay" th:text="|学生评分: ${compWork.studentScore ?: 0}|"></p>
    </div>
    <div class="modal-footer">
      <button class="btn-secondary" id="goBackBtn">返回修改</button>
      <button class="btn-primary" id="finalConfirmBtn">确认提交</button>
    </div>
  </div>
</div>

<!-- 验证码弹窗 -->
<div class="modal-overlay" id="verifyModal">
  <div class="modal-container">
    <div class="modal-header">
      <h3 class="font-bold text-base">验证身份</h3>
      <button class="text-gray-300 hover:text-white" id="closeVerifyModal">
        <i class="fa fa-times"></i>
      </button>
    </div>
    <div class="modal-body">
      <p class="mb-2">请输入右侧验证码完成点赞</p>
      <div class="flex gap-3 items-center mb-2">
        <input type="text" placeholder="输入4位验证码" class="score-input w-1/2" id="verifyCodeInput" maxlength="4">
        <div class="w-1/2 h-10 bg-red-900 rounded-lg flex items-center justify-center text-secondary font-mono text-lg" id="verifyCodeBox">
          <!-- 验证码将通过JS生成 -->
        </div>
        <button class="text-xs text-gray-300 ml-1" id="refreshVerifyCode">
          <i class="fa fa-refresh"></i> 刷新
        </button>
      </div>
      <p class="modal-note text-red-300 hidden" id="verifyError">
        验证码错误，请重新输入
      </p>
    </div>
    <div class="modal-footer">
      <button class="btn-secondary" id="cancelVerifyBtn">取消</button>
      <button class="btn-primary" id="confirmVerifyBtn">确认点赞</button>
    </div>
  </div>
</div>

<!-- 转发提示弹窗 -->
<div class="modal-overlay" id="shareTipModal">
  <div class="modal-container">
    <div class="modal-header">
      <h3 class="font-bold text-base">转发作品</h3>
      <button class="text-gray-300 hover:text-white" id="closeShareTipModal">
        <i class="fa fa-times"></i>
      </button>
    </div>
    <div class="modal-body text-center">
      <i class="fa fa-wechat text-4xl text-green-400 mb-4"></i>
      <p class="mb-2">请通过微信右上角「三个点」转发</p>
      <p class="text-xs text-gray-300">
        1. 点击右上角「...」图标<br>
        2. 选择「转发」选项<br>
        3. 分享给好友或群聊
      </p>
    </div>
    <div class="modal-footer justify-center">
      <button class="btn-primary" id="confirmShareTipBtn">我知道了</button>
    </div>
  </div>
</div>

<!-- 重复点赞提示弹窗 -->
<div class="modal-overlay" id="repeatTipModal">
  <div class="modal-container">
    <div class="modal-header">
      <h3 class="font-bold text-base">温馨提示</h3>
      <button class="text-gray-300 hover:text-white" id="closeRepeatTipModal">
        <i class="fa fa-times"></i>
      </button>
    </div>
    <div class="modal-body text-center py-4">
      <i class="fa fa-info-circle text-secondary text-2xl mb-3"></i>
      <p>今天您已经点过赞了，请明天再来吧</p>
    </div>
    <div class="modal-footer justify-center">
      <button class="btn-primary" id="confirmRepeatTipBtn">我知道了</button>
    </div>
  </div>
</div>

<!-- 重复评分提示弹窗 -->
<div class="modal-overlay" id="repeatScoreModal">
  <div class="modal-container">
    <div class="modal-header">
      <h3 class="font-bold text-base">温馨提示</h3>
      <button class="text-gray-300 hover:text-white" id="closeRepeatScoreModal">
        <i class="fa fa-times"></i>
      </button>
    </div>
    <div class="modal-body text-center py-4">
      <i class="fa fa-info-circle text-secondary text-2xl mb-3"></i>
      <p>您已经评过分了，同一作品同一身份只能评分一次</p>
    </div>
    <div class="modal-footer justify-center">
      <button class="btn-primary" id="confirmRepeatScoreBtn">我知道了</button>
    </div>
  </div>
</div>
<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>

  <script src="../templates/h5/assets/vconsole.min.js"></script>
  <script>
    // var vConsole = new VConsole();
    // console.log('Hello world');
  </script>


<script>
  var workId = 0;
  $(document).ready(function() {
    // 全局变量 - 从Thymeleaf获取初始数据
    workId = [[${compWork.id}]];
    let studentScore = [[${compWork.studentScore ?: 0}]];
    let teacherScore = [[${compWork.teacherScore ?: 0}]];
    let likeCount = [[${compWork.likeCount ?: 0}]];
    let commentCount = [[${compWork.commentCount ?: 0}]];
    let shareCount = [[${compWork.shareCount ?: 0}]];

    // 状态变量
    let currentScoreType = '';
    let currentScoreValue = 0;
    let studentScoreSubmitted = false;
    let teacherScoreSubmitted = false;
    let liked = false;
    let currentVerifyCode = '';
    let currentReplyPid = null; // 当前回复的父评论ID

    // DOM元素
    const $scoreModal = $('#scoreModal');
    const $scoreConfirmModal = $('#scoreConfirmModal');
    const $verifyModal = $('#verifyModal');
    const $shareTipModal = $('#shareTipModal');
    const $repeatTipModal = $('#repeatTipModal');
    const $repeatScoreModal = $('#repeatScoreModal');
    const $commentInput = $('#commentInput');

    // 导航栏切换效果
    $('.nav-item').click(function() {
      $('.nav-item').removeClass('active');
      $(this).addClass('active');
    });

    // 返回按钮事件
    $('.fa-arrow-left').parent().click(function(e) {
      e.preventDefault();
      window.history.back();
    });

    // 视频播放功能
    $('#situationVideoPlaceholder button').click(function() {
      $(this).parent().hide();
      $('#situationVideo').removeClass('hidden').get(0).play();
    });

    $('#speechVideoPlaceholder button').click(function() {
      $(this).parent().hide();
      $('#speechVideo').removeClass('hidden').get(0).play();
    });

    // 评分编辑按钮事件
    $('#editStudentScore').click(function() {
      openScoreModal('student', $(this));
    });

    $('#editTeacherScore').click(function() {
      openScoreModal('teacher', $(this));
    });

    // // 打开评分弹窗
    // function openScoreModal(type, element) {
    //   if ((type === 'student' && studentScoreSubmitted) || (type === 'teacher' && teacherScoreSubmitted)) {
    //     $repeatScoreModal.addClass('active');
    //     return;
    //   }
    //
    //   currentScoreType = type;
    //   currentScoreValue = type === 'student' ? studentScore : teacherScore;
    //
    //   // 更新弹窗内容
    //   $('#modalTitle').text(`${type === 'student' ? '学生' : '教师'}评分`);
    //   $('#modalNote').text(`提示：每个${type === 'student' ? '学生' : '教师'}只能为同一作品评分一次`);
    //   $('#scoreInput').val(currentScoreValue);
    //
    //   // 显示弹窗
    //   $scoreModal.addClass('active');
    //   setTimeout(() => $('#scoreInput').focus(), 300);
    // }



    // 打开评分弹窗
    function openScoreModal(type, element) {
      // 检查登录状态
      if (!checkLoginStatus()) {
        showNoPermissionModal();
        return;
      }


      // 从localStorage获取token并解析用户信息
      const token = localStorage.getItem('token');
      var userType = '';
      let hasPermission = false;

      try {
        if (token) {
          // console.error("localStorage.getItem('token') token: " + token)
          // 解析token中的用户信息（假设token是JSON字符串或包含用户信息的对象）
          //const userInfo = typeof token === 'string' ? JSON.parse(token) : token;
          const userInfo = JSON.parse(token)
          // console.error("localStorage.getItem('token'): " + userInfo)
          userType = userInfo.userType || '';
          console.log("localStorage.getItem('token') userType: " +  userType === '04')

          // 判断用户权限
          if (type === 'student' && userType === '03') {
            hasPermission = true; // 学生评委只能进行学生评分
          } else if (type === 'teacher' && userType === '04') {
            hasPermission = true; // 教师评委只能进行教师评分
          }
        }
      } catch (error) {
        console.error('解析用户信息失败:', error);
      }

      // 检查权限
      if (!hasPermission) {
        // 显示无权限提示
        showNoPermissionModal(`您没有${type === 'student' ? '学生' : '教师'}评分权限`);
        return;
      }





      if ((type === 'student' && studentScoreSubmitted) || (type === 'teacher' && teacherScoreSubmitted)) {
        $repeatScoreModal.addClass('active');
        return;
      }

      currentScoreType = type;
      currentScoreValue = type === 'student' ? studentScore : teacherScore;

      // 更新弹窗内容
      $('#modalTitle').text(`${type === 'student' ? '学生' : '教师'}评分`);
      $('#modalNote').text(`提示：每个${type === 'student' ? '学生' : '教师'}只能为同一作品评分一次`);
      $('#scoreInput').val(currentScoreValue);

      // 显示弹窗
      $scoreModal.addClass('active');
      setTimeout(() => $('#scoreInput').focus(), 300);
    }



    // 显示无权限提示弹窗
    function showNoPermissionModal(message = '您没有执行此操作的权限') {
      // 创建或显示无权限提示弹窗
      let $noPermissionModal = $('#noPermissionModal');

      if ($noPermissionModal.length === 0) {
        // 如果弹窗不存在，创建它
        $noPermissionModal = $(`
      <div id="noPermissionModal" class="modal">
        <div class="modal-content">
          <div class="modal-header">
            <h3>权限不足</h3>
            <span class="close">&times;</span>
          </div>
          <div class="modal-body">
            <p>${message}</p>
            <p>请联系管理员获取相应权限。</p>
          </div>
          <div class="modal-footer">
            <button class="btn-confirm">确定</button>
          </div>
        </div>
      </div>
    `).appendTo('body');

        // 绑定关闭事件
        $noPermissionModal.find('.close, .btn-confirm').on('click', function() {
          $noPermissionModal.removeClass('active');
        });
      } else {
        // 更新提示信息
        $noPermissionModal.find('.modal-body p:first').text(message);
      }

      $noPermissionModal.addClass('active');
    }



    /**
     * 检查登录状态
     */
    function checkLoginStatus() {
      const token = localStorage.getItem("token");
      return token && token !== "" && token !== "undefined";
    }


    // 检查登录状态
    function checkLoginStatus() {
      const token = localStorage.getItem("token");
      return token && token !== "" && token !== "undefined";
    }



    /**
     * 检查评分权限
     * 这里需要根据你的业务逻辑来判断用户是否有评分权限
     * 例如：只有特定角色（教师、评委）才能评分
     */
    function checkScorePermission() {
      // 方法1：从localStorage获取用户角色信息
      const userInfoStr = localStorage.getItem("userInfo");
      if (userInfoStr) {
        try {
          const userInfo = JSON.parse(userInfoStr);
          // 根据你的业务逻辑判断权限
          // 例如：只有角色为teacher或judge的用户可以评分
          const allowedRoles = ['teacher', 'judge', 'admin'];
          if (userInfo.role && allowedRoles.includes(userInfo.role)) {
            return true;
          }
        } catch (e) {
          console.error('解析用户信息失败:', e);
        }
      }

      // 方法2：通过token调用接口验证权限（推荐）
      // 这里需要调用后端接口验证用户权限
      // return verifyUserPermission();

      // 临时方案：默认不允许评分，需要后端配合
      return false;
    }

    /**
     * 显示无权限提示模态框
     */
    function showNoPermissionModal() {
      debugger
      // 创建或显示权限提示模态框
      let $permissionModal = $('#permissionModal');

      if ($permissionModal.length === 0) {
        // 创建权限提示模态框
        $permissionModal = $(`
            <div id="permissionModal" class="modal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 9999; display: flex; align-items: center; justify-content: center;">
                <div class="modal-content" style="background: white; border-radius: 8px; padding: 20px; max-width: 400px; width: 90%;">
                    <div class="modal-header">
                        <h3 style="margin: 0 0 15px 0; color: #333;">权限提示</h3>
                    </div>
                    <div class="modal-body">
                        <p id="permissionMessage" style="margin: 0 0 20px 0; color: #666;">抱歉，您暂无评分权限</p>
                    </div>
                    <div class="modal-footer" style="text-align: right;">
                        <button id="closePermissionModal" class="btn btn-primary" style="padding: 8px 16px; background: #b71211; color: white; border: none; border-radius: 4px; cursor: pointer;">确定</button>
                    </div>
                </div>
            </div>
        `).appendTo('body');

        // 绑定关闭事件 - 使用事件委托，确保能绑定到动态创建的元素
        $(document).on('click', '#closePermissionModal', function() {
          $('#permissionModal').hide();
        });

        // 点击模态框外部关闭
        $permissionModal.on('click', function(e) {
          if (e.target === this) {
            $(this).hide();
          }
        });
      }

      // 根据登录状态显示不同的提示信息
      const message = checkLoginStatus()
              ? '抱歉，您暂无评分权限'
              : '请先登录，登录后可进行相关操作';

      $('#permissionMessage').text(message);
      $permissionModal.show();
    }





    // 关闭评分弹窗
    function closeScoreModal() {
      $scoreModal.removeClass('active');
    }

    // 评分输入变化
    $('#scoreInput').on('input', function() {
      currentScoreValue = parseFloat($(this).val()) || 0;
    });

    // 评分下一步按钮
    $('#nextConfirmBtn').click(function() {
      if (isNaN(currentScoreValue) || currentScoreValue < 1 || currentScoreValue > 100) {
        alert('请输入1-100之间的有效评分');
        return;
      }

      // 更新确认弹窗
      $('#confirmScoreDisplay').text(`${currentScoreType === 'student' ? '学生评分' : '教师评分'}: ${currentScoreValue.toFixed(1)}`);
      closeScoreModal();
      $scoreConfirmModal.addClass('active');
    });

    // 最终确认评分（注意：此处接口未提供，暂用示例）
    $('#finalConfirmBtn').click(function() {
      // 实际项目中需调用评分接口
      $.ajax({
        url: '/h5/comp/work/submitScore', // 假设的评分接口
        type: 'POST',
        data: {
          workId: workId,
          scoreType: currentScoreType,
          score: currentScoreValue
        },
        success: function(response) {
          if (response.code == 0) {
            // 更新本地数据
            if (currentScoreType === 'student') {
              studentScore = currentScoreValue;
              studentScoreSubmitted = true;
              $('#editStudentScore').parent().find('span:first').text(`学生评分: ${currentScoreValue.toFixed(1)}`);
            } else {
              teacherScore = currentScoreValue;
              teacherScoreSubmitted = true;
              $('#editTeacherScore').parent().find('span:first').text(`教师评分: ${currentScoreValue.toFixed(1)}`);
            }
            $scoreConfirmModal.removeClass('active');
          } else {
            alert(response.msg || '评分提交失败');
          }
        },
        error: function() {
          alert('网络错误，评分提交失败');
        }
      });
    });

    // 点赞按钮事件（适配新接口 /h5/like）
    $('#likeBtn').click(function() {

      if (!checkLoginStatus()) {
        showNoPermissionModal();
        return;
      }


      if (liked) {
        $repeatTipModal.addClass('active');
      } else {
        openVerifyModal();
      }
    });

    // 验证码验证通过后提交点赞
    $('#confirmVerifyBtn').click(function() {
      const inputCode = $('#verifyCodeInput').val().trim().toUpperCase();
      if (inputCode === currentVerifyCode) {
        // 验证成功，调用新点赞接口 /h5/like
        $.ajax({
          url: '/h5/comp/work/like',
          type: 'POST',
          data: { workId: workId },
          success: function(response) {
            if (response.code == 0) {
              likeCount++;
              liked = true;
              const formatCount = likeCount >= 1000 ? (likeCount/1000).toFixed(1)+'k' : likeCount;
              $('#likeBtn').addClass('active').find('.action-text').text(`点赞 (${formatCount})`);
              $verifyModal.removeClass('active');
            } else {
              alert(response.msg || '点赞失败');
              if (response.msg.includes('今日已点赞')) {
                $verifyModal.removeClass('active');
                $repeatTipModal.addClass('active');
              }
            }
          },
          error: function() {
            alert('网络错误，点赞失败');
          }
        });
      } else {
        // 验证失败
        $('#verifyError').removeClass('hidden');
        $('#verifyCodeInput').addClass('border-red-500');
        generateVerifyCode();
      }
    });

    // 转发按钮事件（适配新接口 /h5/share）
    $('#shareBtn, #topShareBtn').click(function() {
      //$shareTipModal.addClass('active');

      // 调用新转发接口 /h5/share
      $.ajax({
        url: '/h5/comp/work/share',
        type: 'POST',
        data: {
          workId: workId,
          sharePlatform: '微信' // 默认微信，可扩展其他平台
        },
        success: function(response) {
          if (response.code == 0) {
            shareCount++;
            //$('#shareBtn').find('.action-text').text(`转发 (${shareCount})`);
          }
        }
      });


      // 检查是否微信环境
      if (!navigator.userAgent.toLowerCase().includes('micromessenger')) {
        copyLink();
        return;
      }

      // 获取分享数据
      //const workId = new URLSearchParams(window.location.search).get('id');

      $.get('/h5/user/shareData', { workId: workId }, function(res) {
        console.log('/h5/user/shareData' +JSON.stringify(res))
        if (res.code == 0) {
          console.log('/h5/user/shareData' +JSON.stringify(res))
          initWxShare(res.data);
        }
      });




    });



    // 初始化微信分享
    function initWxShare(shareData) {




      // 获取当前页面URL（必须与后端计算的URL一致）
      const currentUrl = shareData.link;

      // 从后端获取签名配置
      $.get('/h5/user/config?url=' + encodeURIComponent(currentUrl), function(res) {
        if (res.code == 0) {
          const config = res.data;

          wx.config({
            debug: false, // 调试模式，生产环境改为false
            appId: config.appId,
            timestamp: config.timestamp,
            nonceStr: config.nonceStr,
            signature: config.signature,
            jsApiList: [
              'updateAppMessageShareData',
              'updateTimelineShareData',
              'onMenuShareAppMessage',
              'onMenuShareTimeline'
            ]
          });

          wx.ready(function() {
            console.log('微信配置成功！');
            // 朋友分享
            wx.updateAppMessageShareData({
              title: shareData.title,
              desc: shareData.desc,
              link: shareData.link,
              imgUrl: shareData.imgUrl,
              success: function() {
                console.log('朋友分享设置成功');
                console.log('图片URL:', shareData.imgUrl);
              },
              cancel: function() {
                console.log('用户取消分享');
              }
            });

            // 朋友圈分享
            wx.updateTimelineShareData({
              title: shareData.title,
              link: shareData.link,
              imgUrl: shareData.imgUrl,
              success: function() {
                console.log('朋友分享设置成功');
                console.log('图片URL:', shareData.imgUrl);
              },
              cancel: function() {
                console.log('用户取消分享');
              }
            });

            alert('请点击右上角"..."分享给好友');
          });

          wx.error(function(err) {
            console.error('微信配置失败:', err);
            //alert('微信分享配置失败，请重试');
          });

        } else {
          console.error('获取微信配置失败:', res.msg);
        }
      });




      // debugger
      // wx.config({
      //   debug: true,
      //   appId: 'wx3426f7f2264be3ac', // 需要后端提供
      //   timestamp: Date.now(),
      //   nonceStr: 'random_str',
      //   signature: 'signature', // 需要后端计算
      //   jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData']
      // });
      //
      // wx.ready(function() {
      //   // 朋友分享
      //   wx.updateAppMessageShareData({
      //     title: shareData.title,
      //     desc: shareData.desc,
      //     link: shareData.link,
      //     imgUrl: shareData.imgUrl
      //   });
      //
      //   // 朋友圈分享
      //   wx.updateTimelineShareData({
      //     title: shareData.title,
      //     link: shareData.link,
      //     imgUrl: shareData.imgUrl
      //   });
      //
      //   alert('请点击右上角"..."分享给好友');
      // });
    }

// 复制链接（非微信环境）
    function copyLink() {
      const url = window.location.href;
      navigator.clipboard.writeText(url).then(() => {
        alert('链接已复制，可以分享给好友了！');
      }).catch(() => {
        // 兼容旧浏览器
        const input = document.createElement('input');
        input.value = url;
        document.body.appendChild(input);
        input.select();
        document.execCommand('copy');
        document.body.removeChild(input);
        alert('链接已复制，可以分享给好友了！');
      });
    }




    // 评论提交功能（适配新接口 /h5/comment）
    $commentInput.keydown(function(e) {

      if (!checkLoginStatus()) {
        showNoPermissionModal();
        return;
      }


      if (e.keyCode === 13) { // 回车提交
        const content = $(this).val().trim();
        if (!content) {
          alert('评论内容不能为空');
          return;
        }

        // 调用新评论接口 /h5/comment
        $.ajax({
          url: '/h5/comp/work/comment',
          type: 'POST',
          data: {
            workId: workId,
            content: content,
            pid: currentReplyPid || '' // 回复时传递父评论ID，否则为空
          },
          success: function(response) {
            if (response.code == 0) {
              // 清空输入框
              $commentInput.val('');
              currentReplyPid = null; // 重置回复状态

              // 更新评论计数
              commentCount++;
              $('.fa-comments').parent().find('span').text(`在线评论 (${commentCount})`);

              // 刷新评论列表（实际项目中可局部刷新或重新请求接口）
              location.reload(); // 简单处理：刷新页面
            } else {
              alert(response.msg || '评论失败');
            }
          },
          error: function() {
            alert('网络错误，评论失败');
          }
        });
      }
    });

    // 回复按钮事件
    $('.reply-btn').click(function() {
      const commentId = $(this).data('comment-id');
      currentReplyPid = commentId;
      $commentInput.attr('placeholder', '回复这条评论...').focus();
    });

    // 评论点赞功能（假设接口为 /h5/likeComment 和 /h5/cancelCommentLike）
    $('.comment-like-btn').click(function() {
      const $this = $(this);
      const commentId = $this.data('comment-id');

      // 如果已经点赞，则取消点赞
      if ($this.hasClass('text-secondary')) {
        $.ajax({
          url: '/h5/comp/work/cancelCommentLike',
          type: 'POST',
          data: { commentId: commentId },
          success: function(response) {
            if (response.code == 0) {
              let count = parseInt($this.find('span').text().trim());
              count--;
              $this.removeClass('text-secondary').find('span').text(count);
            }
          }
        });
      } else {
        // 否则添加点赞
        $.ajax({
          url: '/h5/comp/work/likeComment',
          type: 'POST',
          data: { commentId: commentId },
          success: function(response) {
            if (response.code == 0) {
              let count = parseInt($this.find('span').text().trim());
              count++;
              $this.addClass('text-secondary').find('span').text(count);
            }
          }
        });
      }
    });

    // 加载更多评论
    $('#loadMoreCommentsBtn').click(function() {
      // 实际项目中调用分页接口加载更多评论
      $(this).text('加载中...');
      setTimeout(() => {
        $(this).text('没有更多评论了');
        $(this).prop('disabled', true).addClass('opacity-50');
      }, 1000);
    });

    // 生成验证码
    function generateVerifyCode() {
      const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
      let code = '';
      for (let i = 0; i < 4; i++) {
        code += chars[Math.floor(Math.random() * chars.length)];
      }
      currentVerifyCode = code;
      $('#verifyCodeBox').text(code);
      $('#verifyCodeInput').val('').removeClass('border-red-500');
      $('#verifyError').addClass('hidden');
    }

    // 打开验证码弹窗
    function openVerifyModal() {
      generateVerifyCode();
      $verifyModal.addClass('active');
      setTimeout(() => $('#verifyCodeInput').focus(), 300);
    }

    // 弹窗关闭事件绑定
    $('#closeModal, #cancelBtn').click(closeScoreModal);
    $scoreModal.click(function(e) {
      if ($(e.target).is(this)) closeScoreModal();
    });

    $('#closeScoreConfirmModal').click(function() {
      $scoreConfirmModal.removeClass('active');
    });

    $('#goBackBtn').click(function() {
      $scoreConfirmModal.removeClass('active');
      $scoreModal.addClass('active');
    });

    $scoreConfirmModal.click(function(e) {
      if ($(e.target).is(this)) $scoreConfirmModal.removeClass('active');
    });

    $('#closeVerifyModal, #cancelVerifyBtn').click(function() {
      $verifyModal.removeClass('active');
    });

    $verifyModal.click(function(e) {
      if ($(e.target).is(this)) $verifyModal.removeClass('active');
    });

    $('#refreshVerifyCode').click(generateVerifyCode);

    $('#closeShareTipModal, #confirmShareTipBtn').click(function() {
      $shareTipModal.removeClass('active');
    });

    $shareTipModal.click(function(e) {
      if ($(e.target).is(this)) $shareTipModal.removeClass('active');
    });

    $('#closeRepeatTipModal, #confirmRepeatTipBtn').click(function() {
      $repeatTipModal.removeClass('active');
    });

    $repeatTipModal.click(function(e) {
      if ($(e.target).is(this)) $repeatTipModal.removeClass('active');
    });

    $('#closeRepeatScoreModal, #confirmRepeatScoreBtn').click(function() {
      $repeatScoreModal.removeClass('active');
    });

    $repeatScoreModal.click(function(e) {
      if ($(e.target).is(this)) $repeatScoreModal.removeClass('active');
    });


    setTimeout(function() {
      const video = $('#situationVideo');
      video.removeClass('hidden');

      const videoElement = video.get(0);
      videoElement.play().then(() => {
        console.log('视频播放成功');
      }).catch(error => {
        console.error('播放失败:', error);
        // 显示错误提示
        //alert('视频自动播放失败，请点击播放！');
      });

    }, 3000); // 延迟3秒

    setTimeout(function() {
      const video = $('#speechVideo');
      video.removeClass('hidden');

      const videoElement = video.get(0);
      videoElement.play().then(() => {
        console.log('视频播放成功');
      }).catch(error => {
        console.error('播放失败:', error);
        // 显示错误提示
        //alert('视频自动播放失败，请点击播放！');
      });

    }, 3000); // 延迟3秒

  });
</script>
</body>
</html>